<!-- src\views\user\UserProfile.vue -->
<template>
  <div class="profile-container">
    <h2>个人信息</h2>
    <el-form :model="userForm" label-width="120px" ref="userFormRef" :rules="userRules" :disabled="!isEditing">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="userForm.realName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="用户身份" prop="role">
        <el-select v-model="userForm.role" placeholder="请选择身份" :disabled="true">
          <el-option label="农民" value="FARMER"></el-option>
          <el-option label="管理人员" value="MANAGER"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="农业领域" prop="agriculturalField" v-if="userForm.role === 'FARMER'">
        <el-radio-group v-model="userForm.agriculturalField">
          <div v-for="group in agriculturalFields" :key="group.title" class="field-group">
            <h3>{{ group.title }}</h3>
            <div v-for="option in group.options" :key="option.value" class="field-option">
              <div class="option-row">
                <el-radio :value="option.value">{{ option.label }}</el-radio>
                <span class="description">{{ option.description }}</span>
              </div>
            </div>
          </div>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="农业机器" prop="agriculturalMachines" v-if="userForm.role === 'FARMER'">
        <el-checkbox-group v-model="userForm.agriculturalMachines" v-if="isEditing">
          <div v-for="group in agriculturalMachines" :key="group.title" class="machine-group">
            <h3>{{ group.title }}</h3>
            <div v-for="option in group.options" :key="option.value" class="machine-option">
              <div class="option-row">
                <el-checkbox :value="option.value">{{ option.label }}</el-checkbox>
                <span class="description">{{ option.description }}</span>
              </div>
            </div>
          </div>
        </el-checkbox-group>
        <div v-else class="tag-container">
          <el-tag
            v-for="machine in userForm.agriculturalMachines"
            :key="machine"
            type="info"
            effect="plain"
            class="machine-tag"
          >
            {{ getMachineLabel(machine) }}
          </el-tag>
          <span v-if="!userForm.agriculturalMachines.length">暂无农业机器</span>
        </div>
      </el-form-item>
    </el-form>
    <div class="profile-footer">
      <el-button type="primary" @click="toggleEdit" v-if="!isEditing">编辑</el-button>
      <el-button type="primary" @click="updateProfile" v-if="isEditing">更新</el-button>
      <el-button @click="cancelEdit" v-if="isEditing">取消</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import axios from '@/plugins/axios';
import { useUserStore } from '@/stores/user';
import { useAgriculturalDataStore } from '@/stores/agriculturalData';

interface UserForm {
  username: string;
  realName: string;
  email: string;
  role: string;
  agriculturalField: string;
  agriculturalMachines: string[];
}

const userStore = useUserStore();
const userForm = ref<UserForm>({
  username: '',
  realName: '',
  email: '',
  role: '',
  agriculturalField: '',
  agriculturalMachines: [],
});
const originalForm = ref<UserForm>({} as UserForm); // 用于取消编辑时恢复数据
const userFormRef = ref<InstanceType<typeof ElForm>>();
const isEditing = ref(false);

const agriculturalDataStore = useAgriculturalDataStore();
const agriculturalFields = agriculturalDataStore.getAgriculturalFields;
const agriculturalMachines = agriculturalDataStore.getAgriculturalMachines;

const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  agriculturalField: [
    {
      required: true,
      message: '请选择农业领域',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (userForm.value.role === 'FARMER' && !value) {
          callback(new Error('请选择农业领域'));
        } else {
          callback();
        }
      },
    },
  ],
};

const getMachineLabel = (value: string) => {
  for (const group of agriculturalMachines) {
    const option = group.options.find((opt) => opt.value === value);
    if (option) return option.label;
  }
  return value;
};

const fetchUserData = async () => {
  try {
    const userId = userStore.user?.id;
    if (!userId) {
      ElMessage.error('用户未登录');
      return;
    }

    const response = await axios.get(`/user/profile?userId=${userId}`);
    if (response.data.code === 200) {
      const data = response.data.data;
      userForm.value = {
        username: data.username,
        realName: data.realName,
        email: data.email,
        role: data.role,
        agriculturalField: data.agriculturalField || '',
        agriculturalMachines: data.agriculturalMachines || [],
      };
      originalForm.value = { ...userForm.value }; // 保存原始数据
    } else {
      ElMessage.error(response.data.message || '获取用户信息失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试');
  }
};

const updateProfile = () => {
  userFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const userId = userStore.user?.id;
        if (!userId) {
          ElMessage.error('用户未登录');
          return;
        }

        const response = await axios.put(`/user/profile?userId=${userId}`, userForm.value);
        if (response.data.code === 200) {
          ElMessage.success('更新成功');
          isEditing.value = false;
          originalForm.value = { ...userForm.value }; // 更新成功后保存新数据
          userStore.setUser(response.data.data); // 更新 store 中的用户信息
        } else {
          ElMessage.error(response.data.message || '更新失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  });
};

const toggleEdit = () => {
  isEditing.value = true;
};

const cancelEdit = () => {
  isEditing.value = false;
  userForm.value = { ...originalForm.value }; // 恢复原始数据
};

onMounted(() => {
  fetchUserData();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1100px;
  margin: 0 auto;
}

.profile-container h2 {
  padding-left: 50%;
}

.profile-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
}

.field-group, .machine-group {
  margin-top: 10px;
  margin-bottom: 10px;
}

.field-group h3, .machine-group h3 {
  font-size: 16px;
  color: #303133;
}

.field-group h3 {
  margin: 0 10px 10px 0;
}

.machine-group h3 {
  margin: 20px 10px 20px 0;
}

.field-option {
  margin-left: 20px;
}

.machine-option {
  margin-left: 20px;
  margin-bottom: 8px;
}

.option-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.description {
  font-size: 12px;
  color: #909399;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.machine-tag {
  margin-right: 10px;
}
</style>